package com.gxg.common.logger;

import com.alibaba.fastjson.JSON;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Logger {
      private static org.slf4j.Logger logger;
      private static  String info;
     static{
         //获得日志，自动判定日志发出者
         StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
         StackTraceElement ste = stackTrace[2];
         info = ste.toString()+":";
         logger = LoggerFactory.getLogger(ste.getClassName());
    }

    public static void debug(String msg) {
         logger.debug(info+msg);
    }
    public static void info(String msg) {
        logger.info(info+msg);
    }
    public static void error(String msg){logger.error(info+msg);}


    /**
     * 消息打印
     * @param origin 来源
     * @param in 入参
     * @param out 出参
     * @param result 执行结果
     */
    public static void  info(String origin,String in,String out,String result){
      logger.info(info+origin+"{'入参':'"+in+"','出参':"+",'"+out+"'},结果为:"+result);
    }
    /**
     * 异常输出
     * @param e
     * @param method
     * @param reason
     */
    public static void exception(Throwable e,String method,String reason){
        logger.error(info+method+"执行发生异常,原因:"+reason,e);
    }
    /**
     * 异常输出
     * @param e
     * @param reason
     */
    public static void exception(Throwable e,String reason){
        logger.error(info+"执行发生异常,原因:"+reason,e);
    }
    /**
     * 调用记录
     * @param request
     * @param obj
     */
    public static void reqLogger(HttpServletRequest request, Object obj) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("请求IP:" + request.getRemoteAddr());
        buffer.append("请求路径:" + request.getPathInfo());
        buffer.append("请求参数:" + JSON.toJSON(obj));
        buffer.append("请求时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        logger.info(buffer.toString());
    }
    /**
     * 返回记录
     * @param request
     * @param obj
     */
    public static void resLogger(HttpServletRequest request, Object obj) {
        StringBuffer buffer = new StringBuffer();
           buffer.append("响应路径:" + request.getPathInfo());
           buffer.append("响应参数:" + JSON.toJSON(obj));
           buffer.append("响应时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
          logger.info(buffer.toString());
    }

}
